package com.inossem.warehousestorage_inossem.activity.refund_storage;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.inossem.utils.base.RegexUtils;
import com.inossem.utils.listener.NoDoubleClickListener;
import com.inossem.utils.log.LogUtils;
import com.inossem.warehousestorage_inossem.R;
import com.inossem.warehousestorage_inossem.activity.base.BaseActivity;
import com.inossem.warehousestorage_inossem.activity.refund_storage.extra.RefundStorageExtra;
import com.inossem.warehousestorage_inossem.bean.refundStorage.RefundStorageBatchListBean;
import com.inossem.warehousestorage_inossem.bean.refundStorage.RefundStorageOverviewBean;
import com.inossem.warehousestorage_inossem.dialog.DialogUtils;
import com.inossem.warehousestorage_inossem.utils.ActivityUtils;
import com.inossem.warehousestorage_inossem.utils.RefundStorageUtils;
import com.zhy.android.percent.support.PercentLinearLayout;
import com.zhy.android.percent.support.PercentRelativeLayout;

import java.util.List;

public class RefundStorageMaterielDetailActivity extends BaseActivity {

    private TextView title, pickingNumber, materielCode, materielDescription, inventoryAddress, moveType, purchaseOrder, reserveNumber;

    private TextView batchNumber, contractCode, supplier, inStorageDate, manufactureDate, validityDate;

    private EditText refundStorageNumber;

    private String mSerial, mPickingNumber, unit;

    private RefundStorageOverviewBean.DataBean.MaterielListBean materielItem;

    private RefundStorageBatchListBean.DataBean.BatchListBean batchItem;

    private PercentRelativeLayout batchInfoLayout;

    private PercentLinearLayout batchListLayout;

    public static final int REQUEST_CODE_BATCH = 100;

    @Override
    protected void onCreateImpl(Bundle savedInstanceState) {
        setContentView(R.layout.activity_refund_storage_materiel_detail);
        initView(RefundStorageMaterielDetailActivity.this);
        initData(RefundStorageMaterielDetailActivity.this);
    }

    private void initView(Activity activity) {
        title = (TextView) activity.findViewById(R.id.headerTitle);
        pickingNumber = (TextView) activity.findViewById(R.id.pickingNumber);
        materielCode = (TextView) activity.findViewById(R.id.materielCode);
        materielDescription = (TextView) activity.findViewById(R.id.materielDescription);
        inventoryAddress = (TextView) activity.findViewById(R.id.inventoryAddress);
        moveType = (TextView) activity.findViewById(R.id.moveType);
        purchaseOrder = (TextView) activity.findViewById(R.id.purchaseOrder);
        reserveNumber = (TextView) activity.findViewById(R.id.reserveNumber);
        batchNumber = (TextView) activity.findViewById(R.id.batchNumber);
        contractCode = (TextView) activity.findViewById(R.id.contractCode);
        supplier = (TextView) activity.findViewById(R.id.supplier);
        inStorageDate = (TextView) activity.findViewById(R.id.inStorageDate);
        manufactureDate = (TextView) activity.findViewById(R.id.manufactureDate);
        validityDate = (TextView) activity.findViewById(R.id.validityDate);
        refundStorageNumber = (EditText) activity.findViewById(R.id.refundStorageNumber);
        batchInfoLayout = (PercentRelativeLayout) activity.findViewById(R.id.batchInfoLayout);
        batchListLayout = (PercentLinearLayout) activity.findViewById(R.id.batchListLayout);
    }

    private void initData(BaseActivity activity) {
        title.setText(activity.getResources().getString(R.string.activity_receive_materiel_detail_title));
        ActivityUtils.initBackAndFunction(activity, R.string.activity_receive_receive_item_title_short, new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                backAndUpdate();
            }
        });
        getExtra(activity);
        getData(activity);
    }

    private void getExtra(Activity activity) {
        mSerial = activity.getIntent().getStringExtra(RefundStorageExtra.SERIAL);
        mPickingNumber = activity.getIntent().getStringExtra(RefundStorageExtra.REFUND_STORAGE_PICKING_NUMBER);
    }

    private void getData(BaseActivity context) {
        materielItem = RefundStorageUtils.getMaterielInformationBySerial(context, mSerial);
        unit = materielItem.getUnit();
        pickingNumber.setText(mPickingNumber);
        materielCode.setText(materielItem.getMaterielCode());
        materielDescription.setText(materielItem.getMaterielDescription());
        inventoryAddress.setText(materielItem.getInventoryAddressCode() + " - " + materielItem.getInventoryAddressValue());
        moveType.setText(materielItem.getMoveType());
        purchaseOrder.setText(materielItem.getPurchaseOrder());
        reserveNumber.setText(materielItem.getReserveNumber());
        refundStorageNumber.setText(TextUtils.isEmpty(materielItem.getRefundNumber()) ? "" : materielItem.getRefundNumber() + unit);
        refundStorageNumber.setOnFocusChangeListener((View v, boolean hasFocus) -> {
            if (hasFocus) {
                refundStorageNumber.setText("");
            }
        });
        batchItem = materielItem.getBatch();
        initBatch(context);
    }

    private void initBatch(Context context) {
        if (batchItem == null) {
            batchNumber.setText("请选择批次");
            batchInfoLayout.setVisibility(View.GONE);
        } else {
            batchNumber.setText(batchItem.getBatchNumber());
            contractCode.setText(batchItem.getContractCode());
            supplier.setText(batchItem.getSupplier());
            inStorageDate.setText(batchItem.getInStorageDate());
            manufactureDate.setText(batchItem.getManufactureDate());
            validityDate.setText(batchItem.getValidityDate());
            List<RefundStorageBatchListBean.DataBean.BatchListBean.BatchInfoListBean> batchInfoList = batchItem.getBatchInfoList();
            batchListLayout.removeAllViews();
            if (batchInfoList != null && !batchInfoList.isEmpty()) {
                for (int i = 0; i < batchInfoList.size(); i++) {
                    RefundStorageBatchListBean.DataBean.BatchListBean.BatchInfoListBean batchInfo = batchInfoList.get(i);
                    RefundStorageUtils.createTextView(context, batchListLayout, batchInfo.getName(), batchInfo.getText());
                }
            }
            batchInfoLayout.setVisibility(View.VISIBLE);
        }

        batchNumber.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                Intent intent = new Intent(context, RefundStorageSelectBatchActivity.class);
                intent.putExtra(RefundStorageExtra.SERIAL, mSerial);
                intent.putExtra(RefundStorageExtra.REFUND_STORAGE_PICKING_NUMBER, mPickingNumber);
                startActivityForResult(intent, REQUEST_CODE_BATCH);
            }
        });
    }

    @Override
    protected void onActivityResultImpl(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_BATCH && resultCode == RESULT_OK) {
            LogUtils.i("收到返回信息");
            batchItem = (RefundStorageBatchListBean.DataBean.BatchListBean) data.getExtras().getSerializable(RefundStorageExtra.BATCH);
            initBatch(RefundStorageMaterielDetailActivity.this);
        }
    }

    private void updateInfo(Context context) {
        RefundStorageUtils.updateMaterielBySerial(context, mSerial, refundStorageNumber.getText().toString().replace(materielItem.getUnit(), "").trim(), batchItem);
    }

    private String check(Context context) {
        String refundStorageNumberStr = refundStorageNumber.getText().toString().replace(materielItem.getUnit(), "").trim();
        if ("".equals(refundStorageNumberStr)) {
            return "退库数量不可以为空";
        }
        if (!RegexUtils.checkDecimal(refundStorageNumberStr)) {
            return "退库数量格式非法";
        }
        float refundStorageNumberFloat = Float.parseFloat(refundStorageNumberStr);
        float canReturnNumberFloat = Float.parseFloat(materielItem.getCanReturnNumber());
        if (refundStorageNumberFloat > canReturnNumberFloat) {
            return "退库库数量不能大于最大可退数量";
        }
        if (batchItem == null) {
            return "请选择批次";
        }
        return null;
    }

    private void backAndUpdate() {
        String checkResult = check(RefundStorageMaterielDetailActivity.this);
        if (checkResult == null) {
            updateInfo(RefundStorageMaterielDetailActivity.this);
            super.onBackPressed();
        } else {
            DialogUtils.getConfirmDialog(RefundStorageMaterielDetailActivity.this, checkResult + "\n" + "是否强制退出?", new DialogUtils.ConfirmDialogListener() {
                @Override
                public void onConfirm(Dialog dialog) {
                    RefundStorageMaterielDetailActivity.super.onBackPressed();
                }
            }).show();
        }
    }

    @Override
    public void onBackPressed() {
        backAndUpdate();
    }
}
